package com.tanxiaoyao.wecon.ui;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParserException;

import com.tanxiaoyao.wecon.R;
import com.tanxiaoyao.wecon.app.AppManager;
import com.tanxiaoyao.wecon.app.UpdateInfo;
import com.tanxiaoyao.wecon.net.UpdateInfoParser;
import com.tanxiaoyao.wecon.net.UpdateManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityAbout extends Activity {

	private static final String TAG = "tanxiaoyao-about";
	private static final Boolean ISDEBUG = false;

	private View about_header;
	private Button checkNewBtn, helpBtn, downloadBtn;
	private TextView versionText;

	private UpdateInfo info;

	private static String versionName;
	private static int versionCode;

	private static final int GET_INFO_SUCCESS = 10;
	private static final int SERVER_ERROR = 11;
	private static final int SERVER_URL_ERROR = 12;
	private static final int IO_ERROR = 13;
	private static final int XML_PARSER_ERROR = 14;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 添加Activity到堆栈
		AppManager.getAppManager().addActivity(this);
		setContentView(R.layout.activity_about);
		// 得到标题栏View对象
		about_header = findViewById(R.id.no_btn_header);
		// 设置标题栏文字
		TextView about_header_title = (TextView) findViewById(R.id.no_btn_header_title);
		about_header_title.setText(R.string.about_title);
		// 取得按钮
		helpBtn = (Button) findViewById(R.id.about_help_btn);
		helpBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 载入markdown 文件
				Intent helpIntent = new Intent();
				helpIntent.setClass(ActivityAbout.this, ActivityUserHelp.class);
				startActivity(helpIntent);
			}
		});
		downloadBtn = (Button) findViewById(R.id.about_download_btn);
		downloadBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Uri sownloadUri = Uri
						.parse("http://git.oschina.net/tanxiaoyao/wecon-release/tree/master/download");
				Intent downloadIntent = new Intent(Intent.ACTION_VIEW,
						sownloadUri);
				startActivity(downloadIntent);
			}
		});
		// 取得升级按钮
		checkNewBtn = (Button) findViewById(R.id.btn_checknew_about);
		checkNewBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 启动一个线程进行服务器连接判断版本号是否相同
				new Thread(new CheckVersionTask()) {
				}.start();
			}
		});
		// 显示版本号
		getLocalVersion();
		versionText = (TextView) findViewById(R.id.version_text);
		versionText.setText("V " + versionName + "\t"
				+ getString(R.string.internal_code) + ": " + versionCode);
	}

	private class CheckVersionTask implements Runnable {
		@Override
		public void run() {
			Message msg = Message.obtain();
			// 取得服务器地址
			String serverUrl = getResources().getString(R.string.serverurl); // 取得服务器地址
			// 连接服务器
			try {
				URL url = new URL(serverUrl);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5000);
				conn.setRequestMethod("GET");
				int code = conn.getResponseCode(); // 取得返回信息
				if (code == 200) {
					InputStream is = conn.getInputStream(); // 取得服务器返回的内容
					info = UpdateInfoParser.getUpdateInfo(is); // 将输入流转换为UpdateInfo对象
					msg.what = GET_INFO_SUCCESS;
					handler.sendMessage(msg);
				} else {
					msg.what = SERVER_ERROR;
					handler.sendMessage(msg);
				}
			} catch (MalformedURLException e) {
				msg.what = SERVER_URL_ERROR;
				handler.sendMessage(msg);
				handler.sendMessage(msg);
			} catch (IOException e) {
				msg.what = IO_ERROR;
				handler.sendMessage(msg);
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				msg.what = XML_PARSER_ERROR;
				handler.sendMessage(msg);
				e.printStackTrace();
			}
		}
	}

	private void getLocalVersion() {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		try {
			PackageInfo packInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			versionName = packInfo.versionName;
			versionCode = packInfo.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case XML_PARSER_ERROR:
				Toast.makeText(getApplicationContext(), "XML解析异常",
						Toast.LENGTH_LONG).show();
				break;
			case IO_ERROR:
				Toast.makeText(getApplicationContext(), "网络异常，请检查网络连接",
						Toast.LENGTH_LONG).show();
				break;
			case SERVER_URL_ERROR:
				Toast.makeText(getApplicationContext(), "服务器URL出错",
						Toast.LENGTH_LONG).show();
				break;
			case SERVER_ERROR:
				Toast.makeText(getApplicationContext(), "服务器异常",
						Toast.LENGTH_LONG).show();
				break;
			case GET_INFO_SUCCESS:
				String serverVersion = info.getVersion(); // 取得服务器上的版本号
				if (versionName.equals(serverVersion)) { // 判断两个版本号是否相同
					Toast.makeText(getApplicationContext(), "当前已经是最新版本",
							Toast.LENGTH_LONG).show();
				} else {
					showUpdateDialog();// 如果版本号不相同，则加载更新对话框
				}
				break;

			default:
				break;
			}
		}

	};

	// 显示升级对话框
	protected void showUpdateDialog() {
		AlertDialog.Builder builder = new Builder(this); // 实例化对话框
		builder.setIcon(getResources().getDrawable(android.R.drawable.btn_dialog)); // 添加图标
		builder.setTitle("升级提示"); // 添加标题
		//设置内容界面
		LayoutInflater layoutInflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		TextView diatxt = (TextView) layoutInflater.inflate(
				R.layout.dialog_view, null);
		diatxt.setText(info.getDescription().replace("\\n", "\n"));
		builder.setView(diatxt);
		//设置按钮
		builder.setPositiveButton("升级", new DialogInterface.OnClickListener() { // 点击升级时的操作方法
					@Override
					public void onClick(DialogInterface dialog, int which) {
						UpdateManager updateManager = new UpdateManager(
								ActivityAbout.this);
						updateManager.checkUpdateInfo();
					}

				});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { // 点击取消时的操作方法
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
					}
				});
		builder.create().show(); // 显示对话框
	}
}
